package com.wanfajie.smsdistribute.db.bean.phone

import com.j256.ormlite.dao.Dao
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
import com.wanfajie.smsdistribute.config.TABLE_PHONE_FIELD_VALUE
import com.wanfajie.smsdistribute.config.TABLE_PHONE_FILED
import com.wanfajie.smsdistribute.db.helper.PhoneDatabaseHelper

@DatabaseTable(tableName = TABLE_PHONE_FIELD_VALUE)
data class PhoneFieldValue(

        @DatabaseField(columnName = PHONE_ID, foreign = true, canBeNull = false)
        var phone: PhoneNumber? = null,

        @DatabaseField(columnName = FIELD_ID, foreign = true, canBeNull = false)
        var field: PhoneKeyField? = null,

        @DatabaseField(columnName = VALUE_FIELD, canBeNull = false, defaultValue = "''")
        var value: String = ""
) {
    companion object {
        const val PHONE_ID = "phone_id"
        const val FIELD_ID = "field_id"
        const val VALUE_FIELD = "value_name"
        const val UNIQUE = "${PHONE_ID}_$FIELD_ID"
        const val TABLE_NAME = TABLE_PHONE_FIELD_VALUE

        val DAO: Dao<PhoneFieldValue, *> = PhoneDatabaseHelper.getDao(PhoneFieldValue::class.java)
    }

    @DatabaseField(columnName = UNIQUE, id = true, generatedId = false, canBeNull = false)
    val unique: String = if (phone != null && field != null) "${phone!!.id}_${field!!.id}" else ""

    val key: String get() {
        val memberField = this.field!!

        return if (memberField.name.isEmpty()) {
            val keyField = PhoneKeyField.DAO.queryForSameId(this.field!!)
            keyField.name
        } else {
            memberField.name
        }
    }
}

@DatabaseTable(tableName = TABLE_PHONE_FILED)
data class PhoneKeyField(
        @DatabaseField(columnName = ID, canBeNull = false, generatedId = true)
        val id: Int = 0,

        @DatabaseField(columnName = NAME, canBeNull = false, unique = true)
        val name: String = ""
) {
    companion object {
        const val ID = "id"
        const val NAME = "field_name"
        const val TABLE_NAME = TABLE_PHONE_FILED

        val DAO: Dao<PhoneKeyField, Int> = PhoneDatabaseHelper.getDao(PhoneKeyField::class.java)

        fun get(name: String): PhoneKeyField {
            val results = DAO.queryForEq(NAME, name)
            return if (results.size > 0) results[0]
            else {
                val keyField = PhoneKeyField(name = name)
                DAO.create(keyField)
                keyField
            }
        }
    }
}
